package ru.ifmo.thesis.solver.gp.dop;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import org.jgap.Chromosome;
import org.jgap.Configuration;
import org.jgap.FitnessFunction;
import org.jgap.Gene;
import org.jgap.Genotype;
import org.jgap.IChromosome;
import org.jgap.InvalidConfigurationException;
import org.jgap.Population;
import org.jgap.event.GeneticEvent;
import org.jgap.event.GeneticEventListener;

import ru.ifmo.thesis.domain.Job;
import ru.ifmo.thesis.domain.Shedule;
import ru.ifmo.thesis.domain.Worker;
import ru.ifmo.thesis.gp.MyConfigurationOptions;
import ru.ifmo.thesis.gp.MyConfigurationOptionsBuilder;
import ru.ifmo.thesis.gp.MyFitnessFunction;
import ru.ifmo.thesis.gp.WorkPlanGene;
import ru.ifmo.thesis.solver.DirectSolver;
import ru.ifmo.thesis.solver.gp.CompletionRule;
import ru.ifmo.thesis.solver.gp.FixedIterations;
import ru.ifmo.thesis.suite.DOPSuiteRunner;
import ru.ifmo.thesis.suite.DOPTaskSuite;
import ru.ifmo.thesis.suite.SuiteRunnerLogger;
import ru.ifmo.thesis.suite.SuiteRunnerXSLXLogger;
import ru.ifmo.thesis.suite.SuiteSerializer;
import ru.ifmo.thesis.suite.DOPSuiteRunner.NextGenerationEvolved;
import ru.ifmo.thesis.suite.DOPSuiteRunner.TaskFinishedEvent;
import ru.ifmo.thesis.suite.DOPSuiteRunner.TaskStartedEvent;
import ru.ifmo.thesis.task.DOPTask;
import ru.ifmo.thesis.task.Task;
import ru.ifmo.thesis.util.Algorithms;
import ru.ifmo.thesis.util.Loggers;

public class DirectDOPGPSolver {

	static Writer w;
	
	public void solve(DOPTask t) throws IOException {
		DirectSolver helper = new DirectSolver();
		
		List<Worker> workers = t.getWorkers();
		List<Job> initialTasks = t.getInitialJobs();
		List<Job> additional = t.getAdditionalJobs();
		
		while (!additional.isEmpty()) {
			Shedule solve = helper.solve(new Task(workers, initialTasks));
			System.out.println("VALUE = " + Algorithms.calculateSheduleCost(solve));
			w.write("VALUE = " + Algorithms.calculateSheduleCost(solve) + "\n");
			initialTasks.add(additional.remove(0));
		}
	}
	
	public static void main(String[] args) throws Exception {
//		Loggers.initDefaultConsoleLogger();
		DOPTaskSuite taskSuite = SuiteSerializer.readZippedDOPSuite(
				new FileInputStream("tasks/suite-DOP-A-1.zip"));
		
		w = new FileWriter("mySimpleLog.txt");

		DirectDOPGPSolver solver = new DirectDOPGPSolver();
		
		for (DOPTask t : taskSuite.getTasks()) {
			
			System.err.println("next task");
			
			long start = System.nanoTime();
			solver.solve(t);
			System.err.println("time = " + (System.nanoTime() - start));
		}
		
		w.close();
		
	}
}
